<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts 主题

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    chartData: {
      type: Object,
      default: () => ({
        categories: ['婴幼儿', '保健品', '美妆', '贵金属', '服饰', '特产'],
        values: [5, 7, 15, 18, 20, 29]
      })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ categories, values } = this.chartData) {
      // 构建雷达图的指示器
      const indicator = categories.map((category, index) => {
        return {
          name: category,
          max: 30
        }
      })

      this.chart.setOption({
        title: {},
        radar: {
          indicator: indicator,
          shape: 'polygon',
          splitNumber: 4, // 分割的圈数
          name: {
            textStyle: {
              color: '#fff'
            }
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(0, 255, 255, 0.3)'
            }
          },
          splitArea: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(0, 255, 255, 0.3)'
            }
          }
        },
        series: [{
          name: '购物品类占比',
          type: 'radar',
          data: [
            {
              value: values,
              name: '占比',
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: 'rgba(0, 255, 255, 0.8)' },
                  { offset: 1, color: 'rgba(0, 255, 255, 0.1)' }
                ])
              },
              lineStyle: {
                color: 'rgba(0, 255, 255, 0.8)',
                width: 1
              },
              itemStyle: {
                color: '#00ffff',
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: true,
                formatter: '{c}%',
                color: '#fff'
              },
              symbolSize: 6
            }
          ]
        }]
      })
    }
  }
}
</script>
